package com.example.rabbitmq.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author : zhayh
 * @date : 2021-5-4 21:33
 * @description :
 */

@Slf4j
@RestController
@RequestMapping("/api")
public class RabbitMQController {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/direct/producer")
    public ResponseEntity<String> directProducer(String exchangeName, String routingKey, String message) {
        rabbitTemplate.convertAndSend(exchangeName, routingKey, message);
        return ResponseEntity.ok(String.format("%s交换机发送消息成功，%s队列的消息内容为%s",
                exchangeName, routingKey, message));
    }

    @GetMapping("/fanout/producer")
    public ResponseEntity<String> fanoutProducer(String exchangeName, String message) {
        rabbitTemplate.convertAndSend(exchangeName, "", message);
        return ResponseEntity.ok(String.format("%s交换机发送消息成功，内容为%s",
                exchangeName, message));
    }

    @GetMapping("/topic/producer")
    public ResponseEntity<String> topicProducer(String exchangeName, String routingKey, String message) {
        rabbitTemplate.convertAndSend(exchangeName, routingKey, message);
        return ResponseEntity.ok(String.format("%s交换机发送消息成功，内容为%s",
                exchangeName, message));
    }

    @GetMapping("/header/producer")
    public ResponseEntity<String> headerProducer(String exchangeName, String department, String message) {
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("department", department);
        MessageConverter messageConverter = new SimpleMessageConverter();
        Message msg = messageConverter.toMessage(message, messageProperties);
        rabbitTemplate.send(exchangeName, "", msg);
        return ResponseEntity.ok(String.format("%s交换机发送消息成功，内容为%s",
                exchangeName, message));
    }

    @RabbitListener(queues = "marketingQueue")
    public void listenMarketing(String message) {
        log.info("监听到的marketing队列的消息： {}", message);
    }
    @RabbitListener(queues = "financeQueue")
    public void listenFinance(String message) {
        log.info("监听到的finance队列的消息： {}", message);
    }
    @RabbitListener(queues = "adminQueue")
    public void listenAdmin(String message) {
        log.info("监听到的admin队列的消息： {}", message);
    }
}
